//  手写一个简单的promise 加深理解
const PENDING = "pending"
const FULFILLED = "fulfilled"
const REJECTED = "rejected"
class MyPromise{
	#status = PENDING
	#result = undefined
	constructor(executor){
		const  resolved = (data)=> this.#changeStatus(FULFILLED,data)
		const  rejected = (reason) => this.#changeStatus(REJECTED,reason)
		// promise 内部 异步操作抛出异常，promise 无法捕获,无法改变promise 状态 ,promise状态还是pending state还是undefined
		// 原因就是 promise 内部 try-catch 机制无法捕获异步异常
		try {
			executor(resolved,rejected)
		} catch (error) {
			rejected(error)
		}
	}
	#changeStatus(status,result){
		if(this.#status!==PENDING){
			return;
		}
		this.#status = status;
		this.#result = result;
		console.log(this.#result,this.#status);
	}
}

const p3 = new MyPromise((res,reject)=>{
	// res(2)
	// reject(3)
	throw 123
	// setTimeout(()=>{
	// 	throw 123;
	// },100)
})
// console.log(p3);

//借助ES2015现有的promise 实现异步编程 ,防止回调函数造成回调地狱现象,不利于项目后期维护
const p1 = new Promise((resolved,rejected)=>{
	// setTimeout(()=>{throw 134;},1000)
	// promise 内部 异步操作抛出异常，promise 无法捕获,无法改变promise 状态 ,promise状态还是pending state还是undefined
	rejected("异常")
	// resolved(1)
	
})
p1.catch(err=> console.log(err))